import React, { useState, useEffect, useRef } from 'react';
import { View, Text, Input, Button, ScrollView } from '@tarojs/components';
import Taro from '@tarojs/taro';
import { useAppStore } from '../../../store';
import { aiApi } from '../../../services/api';
import { ChatMessage } from '../../../types';
import { formatRelativeTime, generateId } from '../../../utils';
import './index.scss';

const AIChatPage = () => {
  const { chatMessages, addChatMessage, setChatMessages } = useAppStore();
  const [inputMessage, setInputMessage] = useState('');
  const [isLoading, setIsLoading] = useState(false);
  const scrollViewRef = useRef<any>(null);

  // 预设问题
  const presetQuestions = [
    '我最近的心情变化是什么样的？',
    '我在工作上有什么进步吗？',
    '我最常写的话题是什么？',
    '我的写作风格有什么特点？',
    '我需要关注哪些方面的成长？'
  ];

  // 加载历史对话
  useEffect(() => {
    loadConversations();
  }, []);

  // 自动滚动到底部
  useEffect(() => {
    if (chatMessages.length > 0) {
      scrollToBottom();
    }
  }, [chatMessages]);

  const loadConversations = async () => {
    try {
      const response = await aiApi.getConversations();
      if (response.success && response.data) {
        setChatMessages(response.data);
      }
    } catch (error) {
      console.error('加载对话历史失败:', error);
    }
  };

  const scrollToBottom = () => {
    setTimeout(() => {
      if (scrollViewRef.current) {
        scrollViewRef.current.scrollTop = scrollViewRef.current.scrollHeight;
      }
    }, 100);
  };

  const handleSendMessage = async () => {
    const message = inputMessage.trim();
    if (!message) return;

    // 添加用户消息
    const userMessage = {
      id: generateId(),
      role: 'user',
      content: message,
      timestamp: new Date().toISOString(),
    };
    addChatMessage(userMessage);
    setInputMessage('');
    setIsLoading(true);

    try {
      const response = await aiApi.chat(message);
      if (response.success && response.data) {
        // 添加AI回复
        const aiMessage = {
          id: generateId(),
          role: 'assistant',
          content: response.data.answer,
          timestamp: new Date().toISOString(),
          related_diaries: response.data.related_diaries,
        };
        addChatMessage(aiMessage);
      } else {
        // 添加错误消息
        const errorMessage = {
          id: generateId(),
          role: 'assistant',
          content: '抱歉，我现在无法回答你的问题。请稍后再试。',
          timestamp: new Date().toISOString(),
        };
        addChatMessage(errorMessage);
      }
    } catch (error) {
      console.error('发送消息失败:', error);
      const errorMessage = {
        id: generateId(),
        role: 'assistant',
        content: '网络连接失败，请检查网络后重试。',
        timestamp: new Date().toISOString(),
      };
      addChatMessage(errorMessage);
    } finally {
      setIsLoading(false);
    }
  };

  const handlePresetQuestion = (question) => {
    setInputMessage(question);
  };

  const handleViewRelatedDiary = (diaryId) => {
    Taro.navigateTo({
      url: `/pages/diary/detail/index?id=${diaryId}`,
    });
  };

  return (
    <View className="ai-chat-page">
      {/* 顶部标题 */}
      <View className="header">
        <Text className="title">🤖 与过去的自己对话</Text>
        <Text className="subtitle">基于你的日记内容，AI会模拟过去的你来回答问题</Text>
      </View>

      {/* 聊天区域 */}
      <ScrollView
        ref={scrollViewRef}
        className="chat-area"
        scrollY
        scrollTop={999999}
        scrollWithAnimation
      >
        {chatMessages.length === 0 ? (
          <View className="welcome-message">
            <View className="welcome-icon">🌟</View>
            <Text className="welcome-title">开始与过去的自己对话吧！</Text>
            <Text className="welcome-desc">
              你可以问我关于你的心情变化、成长轨迹、写作风格等任何问题
            </Text>
            
            {/* 预设问题 */}
            <View className="preset-questions">
              <Text className="preset-title">试试这些问题：</Text>
              {presetQuestions.map((question, index) => (
                <View
                  key={index}
                  className="preset-question"
                  onClick={() => handlePresetQuestion(question)}
                >
                  <Text className="preset-text">{question}</Text>
                </View>
              ))}
            </View>
          </View>
        ) : (
          <View className="message-list">
            {chatMessages.map((message) => (
              <View
                key={message.id}
                className={`message ${message.role === 'user' ? 'user-message' : 'ai-message'}`}
              >
                <View className="message-content">
                  <View className="message-bubble">
                    <Text className="message-text">{message.content}</Text>
                    {message.related_diaries && message.related_diaries.length > 0 && (
                      <View className="related-diaries">
                        <Text className="related-title">相关日记：</Text>
                        {message.related_diaries.map((diaryId) => (
                          <View
                            key={diaryId}
                            className="related-diary"
                            onClick={() => handleViewRelatedDiary(diaryId)}
                          >
                            <Text className="diary-link">📖 查看日记 #{diaryId}</Text>
                          </View>
                        ))}
                      </View>
                    )}
                  </View>
                  <Text className="message-time">
                    {formatRelativeTime(message.timestamp)}
                  </Text>
                </View>
              </View>
            ))}
            
            {isLoading && (
              <View className="message ai-message">
                <View className="message-content">
                  <View className="message-bubble typing">
                    <View className="typing-indicator">
                      <View className="typing-dot"></View>
                      <View className="typing-dot"></View>
                      <View className="typing-dot"></View>
                    </View>
                  </View>
                </View>
              </View>
            )}
          </View>
        )}
      </ScrollView>

      {/* 输入区域 */}
      <View className="input-area">
        <View className="input-container">
          <Input
            className="message-input"
            placeholder="输入你想问的问题..."
            value={inputMessage}
            onInput={(e) => setInputMessage(e.detail.value)}
            onConfirm={handleSendMessage}
            confirmType="send"
          />
          <Button
            className="send-btn"
            onClick={handleSendMessage}
            disabled={!inputMessage.trim() || isLoading}
          >
            发送
          </Button>
        </View>
        
        {/* 快捷操作 */}
        <View className="quick-actions">
          <Button
            className="action-btn"
            size="mini"
            onClick={() => setChatMessages([])}
          >
            🗑️ 清空对话
          </Button>
          <Button
            className="action-btn"
            size="mini"
            onClick={() => Taro.switchTab({ url: '/pages/diary/list/index' })}
          >
            📚 查看日记
          </Button>
        </View>
      </View>
    </View>
  );
};

export default AIChatPage; 